package com.tozed.android.launcher.simpleui;

import java.util.ArrayList;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;

import com.tozed.android.launcher.CellLayout;
import com.tozed.android.launcher.Folder;
import com.tozed.android.launcher.LauncherApplication;
import com.tozed.android.launcher.PagedView;
import com.tozed.android.launcher.R;

public class SimpleWorkspace extends PagedView
{
	private static final String TAG = "SimpleWorkspace";
	public static final int DEFAULT_SCREEN = 0;
	private static final int FINISH_CHANGE_STATE_ANI = 2;
	private static final float MAX_SWIPE_ANGLE = 1.047198F;
	private static final float START_DAMPING_TOUCH_SLOP_ANGLE = 0.5235988F;
	private static final float TOUCH_SLOP_DAMPING_FACTOR = 4.0F;
	//private static final int TOUCH_STATE_REST = 0;
	private ValueAnimator mAnimWithInterpolator;
	private boolean mChangeStateAnimatingIsEnd = true;
	private int mDefaultScreen = 0;
	private long mDuration;
	private float mEditModeShrinkFactor;
	private float mEditModeTranslationY;
	private Context mContext;
	
	Handler mHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			case FINISH_CHANGE_STATE_ANI:
				Log.e(TAG, ">>>>>>>>>>>>>>>FINISH_CHANGE_STATE_ANI");
				if (mContext instanceof SimpleUILauncher){
					((SimpleUILauncher)mContext).invalidateBubbleTextViews();
				}
			}
		}
	};
	
	private boolean mIsSwitchingState = false;
	//private MultiTouchIntercepter mMultiToucher;
	private float[] mNewScaleXs; // 长按支持缩放
	private float[] mNewScaleYs;
	private float[] mNewTranslationYs;
	private float[] mOldScaleXs;
	private float[] mOldScaleYs;
	private float[] mOldTranslationYs;
	private Paint mPaint = new Paint();
	private int mScreenCount;
	private SimpleIconCache mSimpleIconCache;
	private SimpleUILauncher mSimpleUILauncher;
	private int mTouchState = 0;
	private float mXDown;
	private float mYDown;

	public SimpleWorkspace(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		mContext = context;
		
		initWorkspace();
		setChildrenDrawnWithCacheEnabled(true);
	    setChildrenDrawingCacheEnabled(true);
	}

	private void initWorkspace(){
		Resources res = getContext().getResources();
		mCurrentPage = this.mDefaultScreen;
		//mMultiToucher = new MultiTouchIntercepter(this);
		mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
		mSimpleIconCache = LauncherApplication.getActiveInstance().getSimpleIconCache();
		
		mEditModeShrinkFactor = (res.getInteger(R.integer.simple_edit_mode_shrink_factor) / 100.0F);
		
		// 缩放后Y轴向上移动给Page Indicatior 留出空间
		mEditModeTranslationY = (-1.0F * res.getDimensionPixelSize(R.dimen.simple_edit_mode_translation));
		
		// PagedView数据准备好了
		setDataIsReady();
		
		mFadeInAdjacentScreens = false;
		mDuration = res.getInteger(R.integer.simple_workspace_state_change_duration);
	}
	
	// 增加应用到原始的位置
	public boolean addItemInfoToOriPisition(SimpleApplicationInfo app)
	{
		SimpleCellLayout cellLayout = (SimpleCellLayout)getChildAt(app.screen);
		if (cellLayout == null)
			return false;
			
		View view;
		SimpleItemInfo itemInfo;
		
		view = cellLayout.getChildAt(app.cellX, app.cellY);
		if (view == null)
			return false;
		
		Object tag = view.getTag();
		if (tag instanceof SimpleItemInfo){
			itemInfo = (SimpleItemInfo)tag;
			
			if (itemInfo.itemType == SimpleLauncherSettings.SimpleFavorites.ITEM_TYPE_NEED_ADDED){
				cellLayout.removeView(view);
			}
			
			SimpleLauncherModel.sFavoriteItems.remove(itemInfo);
			View newView = mSimpleUILauncher.createBubbleView(R.layout.simple_bubble_view, cellLayout, app);
			// spanX, spanY 横向跨度和纵向跨度都为1
		    addViewInScreen(newView, app.screen, app.cellX, app.cellY, app.spanX, app.spanY, false);
		    return true;
		}else{
			return false;
		}
	}
	
	// 添加视图到指定屏幕中,并指定行列坐标及横纵跨度
	public void addViewInScreen(View childView, int screen, int cellX, int cellY, int spanX, int spanY, boolean isInFolder)
	{
		SimpleCellLayout cellLayout = (SimpleCellLayout)getChildAt(screen);
	    if (cellLayout == null){
	      Log.w(TAG, "add view to screen failed layout screen=" + screen + " is null, layout count= " + getChildCount() 
	    		  + " isInFolder=" + isInFolder + " x=" + cellX + " y=" + cellY);
	      return;
	    }
	    
	    ViewGroup.LayoutParams genericLp = childView.getLayoutParams();
	    SimpleCellLayout.LayoutParams lp = null;
	    
	    if (genericLp == null || !(genericLp instanceof SimpleCellLayout.LayoutParams)) {
	    	lp = new SimpleCellLayout.LayoutParams(cellX, cellY, spanX, spanY);
        } else {
        	lp = (SimpleCellLayout.LayoutParams)genericLp;
        	lp.cellX = cellX;
        	lp.cellY = cellY;
        	lp.cellHSpan = spanX;
        	lp.cellVSpan = spanY;
        }
	    
	    if (spanX < 0 && spanY < 0) {
	    	lp.isLockedToGrid = false;
        }
	    
	    // 设定占位标志
	    for (int x = cellX; x < cellX + spanX && x < SimpleCellLayout.SIMPLEUI_COUNTX; x++) {
            for (int y = cellY; y < cellY + spanY && y < SimpleCellLayout.SIMPLEUI_COUNTY; y++) {
            	cellLayout.setOccupied(x, y);
            }
        }
	    
	    // 取消触觉反馈
	    childView.setHapticFeedbackEnabled(false);
	    
	    // 把view直接添加到CellLayout中
	    if (!cellLayout.addViewToCellLayout(childView, -1, lp, true)){
	    	Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout");
	    }
	    
	    if (mContext instanceof SimpleUILauncher)
	    	childView.setOnLongClickListener((OnLongClickListener)mContext);
	    
		requestLayout();
	}
	
	// 改变状态: 正常或者编辑状态
	public void changeState(SimpleUILauncher.State state)
	{
	    if (mContext instanceof SimpleUILauncher)
	    	((SimpleUILauncher)mContext).setMode(state);
	}
	
	// 状态改变动画(从正常状态到编辑状态)
	public void changeStateAnimated(final SimpleUILauncher.State state)
	{
		mChangeStateAnimatingIsEnd = false;
		changeState(state);
		
		Log.e(TAG, "changeStateAnimated state=" + state);
		
		final float cellLayoutTranslationY;

		float start;
		float end;
		if (state == SimpleUILauncher.State.EDIT){
			//start = mEditModeShrinkFactor;
			//end = mEditModeTranslationY;
			start = 1.0F;
			end = 0.9f;
			cellLayoutTranslationY = mEditModeTranslationY;
		}else{
			//start = 1.0F;
			//end = 0.0F;
			start = 0.9F;
			end = 1.0F;
			cellLayoutTranslationY = (-1*mEditModeTranslationY);
		}
		
		mScreenCount = getChildCount();
		initAnimationArrays();
		for (int i = 0; i < mScreenCount; i++)
		{
			SimpleCellLayout cellLayout = (SimpleCellLayout) getChildAt(i);
			cellLayout.setPivotY(cellLayout.getHeight() / 2.0F);
			cellLayout.setPivotX(cellLayout.getWidth() / 2.0F);
			mOldScaleXs[i] = cellLayout.getScaleX();
			mOldScaleYs[i] = cellLayout.getScaleY();
			mOldTranslationYs[i] = cellLayout.getTranslationY();
			mNewScaleXs[i] = start;
			mNewScaleYs[i] = start;
			mNewTranslationYs[i] = end;
		}
		
		
		if (mAnimWithInterpolator == null)
		{
			// 动画持续时间300ms, 从0.0到1.0一般返回30帧
			//mAnimWithInterpolator = ValueAnimator.ofFloat(new float[] { 0.0F, 1.0F }).setDuration(mDuration);
			mAnimWithInterpolator = ValueAnimator.ofFloat(start, end).setDuration(mDuration);
			
			//  清除之前的监听
			mAnimWithInterpolator.removeAllListeners();
		    mAnimWithInterpolator.removeAllUpdateListeners();
		}else{
			mAnimWithInterpolator = ValueAnimator.ofFloat(start, end).setDuration(mDuration);
			//  清除之前的监听
			mAnimWithInterpolator.removeAllListeners();
			mAnimWithInterpolator.removeAllUpdateListeners();
			
		}
		
		// 监听动画结束事件
		mAnimWithInterpolator.addListener(new AnimatorListenerAdapter()
		{
			@Override
			public void onAnimationEnd(Animator animator)
			{
				Log.e(TAG, ">>>>>onAnimationEnd ");
				
				if (mContext instanceof SimpleUILauncher)
				{
					// 动画完成后显示或隐藏删除按钮图标
					mHandler.sendEmptyMessageDelayed(FINISH_CHANGE_STATE_ANI, 100);
					if (mContext instanceof SimpleUILauncher){
						Log.e(TAG, ">>>>>onAnimationEnd, mContext is SimpleUILauncher");
						((SimpleUILauncher)mContext).getSimplePageIndicatior().setVisibility(View.VISIBLE);
						((SimpleUILauncher)mContext).layoutNavigationPoint();
					}
				}else{
					Log.e(TAG, ">>>>>onAnimationEnd, mContext not SimpleUILauncher");
				}
				
				int count = getChildCount();
				for (int i = 0; i < count; i++)
				{
					View view = ((SimpleCellLayout)getChildAt(i)).getChildAt(0, 0);
					if (view instanceof SimpleLauncherAppWidgetHostView){
						SimpleLauncherAppWidgetHostView appWidgetHost = (SimpleLauncherAppWidgetHostView)view;
						appWidgetHost.setState(state);
						
						if (state == SimpleUILauncher.State.EDIT)
							appWidgetHost.setOnClickListener(mSimpleUILauncher);
					}
				}
			}
		});
		
		
		// 监听帧动画更新(缩放CellLayout视图关键)
		final float scaleX = start;
		final float scaleY = end;
		mAnimWithInterpolator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
		{
			@Override
			public void onAnimationUpdate(ValueAnimator animator)
			{
				Float value = (Float)animator.getAnimatedValue();
				//Log.e(TAG, ">>>>>onAnimationUpdate, value=" + value);
				
				// 把所有screen都缩放
				for (int i = 0; i < mScreenCount; i++)
				{
					SimpleCellLayout cellLayout = (SimpleCellLayout)getChildAt(i);
					if (cellLayout != null){
						//cellLayout.setScaleX(scaleX*mOldScaleXs[i] + scaleY*mNewScaleXs[i]);
						//cellLayout.setScaleY(scaleX*mOldScaleYs[i] + scaleY*mNewScaleYs[i]);
						//cellLayout.setTranslationY(scaleX*mOldTranslationYs[i] + scaleY*mNewTranslationYs[i]);
						
						// 设置横向缩放
						cellLayout.setScaleX(value);
						// 设置横向缩放
						cellLayout.setScaleY(value);
						// 设置纵向偏移
						cellLayout.setTranslationY(value*cellLayoutTranslationY);
					}else{
						Log.w(TAG, "SimpleWorkspace CellLayout is null");
					}
				}
			}
		});
			
		AnimatorSet animatorSet;
		ValueAnimator editAnimtor = mSimpleUILauncher.getEditAnimtor();
		animatorSet = new AnimatorSet();
		animatorSet.addListener(new AnimatorListenerAdapter(){
			 public void onAnimationEnd(Animator paramAnimator){
				 mChangeStateAnimatingIsEnd = true;
				 Log.e(TAG, ">>>>>animatorSet onAnimationEnd");
		     }
		});
	    
		if (editAnimtor == null)
			animatorSet.play(mAnimWithInterpolator);
		else
			animatorSet.playTogether(new Animator[]{mAnimWithInterpolator, editAnimtor});
		
		animatorSet.start();
	}
	
	// 清除子视图
	public void clearChildren()
	{
		int count = getChildCount();
		for (int i = 0; i < count; i++){
			SimpleCellLayout cellLayout = (SimpleCellLayout)getChildAt(i);
			if (cellLayout != null)
				cellLayout.removeAllViews();
		}
		
		mContext = null;
	}
	
	public void computeScroll(){
	    super.computeScroll();
	}
	
	protected void determineScrollingStart(MotionEvent event)
	{
		float scaleX;
	    float scaleY;
	    float slopScale = 0;
	    
	    if (!mIsSwitchingState)
	    {
	      scaleX = Math.abs(event.getX() - mXDown);
	      scaleY = Math.abs(event.getY() - mYDown);
	      if (Float.compare(scaleX, 0.0F) != 0){
	    	  slopScale = (float)Math.atan(scaleY / scaleX);
	      }
	      
	      if (slopScale > 1.047198F) 
	    	  return;	  
	      
	      if (slopScale > 0.5235988F){
		      super.determineScrollingStart(event, 1.0F + 4.0F * (float)Math.sqrt((slopScale - 0.5235988F) / 0.5235988F));
		      return;
		  }
	    }
	    
	    super.determineScrollingStart(event);
	}
	
	protected void dispatchDraw(Canvas canvas){
	    super.dispatchDraw(canvas);
	}
	
	public boolean dispatchUnhandledMove(View focused, int direction)
	{
		if (direction == 17)
		{
	      if (getCurrentScreen() > 0){
	        snapToPage(-1 + getCurrentScreen());
	        return true;
	      }
	    } 
		else if ((direction == 66) && (getCurrentScreen() < getChildCount() - 1))
	    {
	      snapToPage(1 + getCurrentScreen());
	      return true;
	    }
		
	    return super.dispatchUnhandledMove(focused, direction);
	}
	
	public void focusableViewAvailable(View focused)
	{
		View curPageView = getChildAt(mCurrentPage);
		View v = focused;
        while (true) {
            if (v == curPageView) {
                super.focusableViewAvailable(focused);
                return;
            }
            if (v == this) {
                return;
            }
            ViewParent parent = v.getParent();
            if (parent instanceof View) {
                v = (View)v.getParent();
            } else {
                return;
            }
        }
	}
	
	public boolean getChangeStateAnimatingIsEnd(){
		return mChangeStateAnimatingIsEnd;
	}

	public int getCurrentScreen(){
		return mCurrentPage;
	}
	
	// 根据包名和类名来查找应用视图
	public View getIconView(String strPkgName, String strClsName)
	{
		int pageCount = getChildCount();
		for (int i = 0; i < pageCount; i++)
	    {
	      SimpleCellLayout cellLayout = (SimpleCellLayout)getChildAt(i);
	      int cellViewCount = cellLayout.getChildCount();
	      
	      for (int j = 0; j < cellViewCount; j++)
	      {
	        View cellView = cellLayout.getChildAt(j);
	        if (cellView instanceof SimpleBubbleView)
	        {
	        	SimpleItemInfo itemInfo = (SimpleItemInfo)cellView.getTag();
	        	String str1 = itemInfo.getPkgName();
	        	
	        	if (str1 != null && str1.equalsIgnoreCase(strPkgName)){
	        		String str2 = itemInfo.getClsName();
	        		 if (str2 != null && str2.equalsIgnoreCase(strClsName))
	       	          	return cellView;
	        	}
	        }
	      }
	    }
	    
	    return null;
	}
	
	// 初始化动画数组
	void initAnimationArrays()
	{
	    int childCount = getChildCount();
	    mOldScaleXs = new float[childCount];
	    mOldScaleYs = new float[childCount];
	    mNewScaleXs = new float[childCount];
	    mNewScaleYs = new float[childCount];
	    mOldTranslationYs = new float[childCount];
	    mNewTranslationYs = new float[childCount];
	}
	
	protected void loadAssociatedPages(int paramInt, boolean paramBoolean){
		// TODO: 无需实现
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent ev){
		return super.onTouchEvent(ev);
	}
	
	public void onTouchLarge(){
		// TODO: 无需实现
	}

	public void onTouchSmall(){
		// TODO: 无需实现
	}
	
	// 拦截触摸事件
	// 返回True（代表事件在当前的viewGroup中会被处理）,则向下传递之路被截断（所有子控件将没有机会参与Touch事件）
	// 同时把事件传递给当前的控件的onTouchEvent()处理；
	// 返回false, 则把事件交给子控件的onInterceptTouchEvent()
	@Override
	public boolean onInterceptTouchEvent(MotionEvent event)
	{
		if (event.getPointerCount() >= 2)
			return true;
		
		switch (event.getAction() & MotionEvent.ACTION_MASK)
		{
		case MotionEvent.ACTION_DOWN:
			Log.i(TAG,"onInterceptTouchEvent MotionEvent.ACTION_DOWN..................");
			mXDown = event.getX();
			mYDown = event.getY();
			setAllowLongPress(true); // new add
			break;
			
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_POINTER_UP:
			Log.i(TAG,"onInterceptTouchEvent MotionEvent.ACTION_UP...................");
			if (this.mTouchState == 0)
				onUnhandledTap(event);
			//mMultiToucher.endMultiTouch();
			setAllowLongPress(false);
			break;
			
		default:
			return super.onInterceptTouchEvent(event);
		}
		
		return false;
	}
	
	@Override
	protected Parcelable onSaveInstanceState()
	{
		SavedState savedState = new SavedState(super.onSaveInstanceState());
		savedState.currentScreen = mCurrentPage; // mCurrentPage为其父类PagedView参数
	    return savedState;
	}
	
	@Override
	protected void onRestoreInstanceState(Parcelable state)
	{
		//super.onRestoreInstanceState(state); // 返回的时候会出错
		
		try{
			super.onRestoreInstanceState(state);
			
			SavedState savedState = (SavedState)state;
			if (savedState.currentScreen != -1){
				mCurrentPage = savedState.currentScreen;
				if (mContext instanceof SimpleUILauncher){
					((SimpleUILauncher)mContext).getSimplePageIndicatior().setCurrentScreen(mCurrentPage);
				}else if (mContext instanceof SimpleFolder){
					((SimpleFolder)mContext).getSimplePageIndicatior().setCurrentScreen(mCurrentPage);
				}
			}
		} catch (Exception e){
			
		}
		
		state = null;
	}
	
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh)
	{
		if ((h != oldh) && (mContext instanceof SimplePageIndicator.NaviPointLayoutChange))
		   ((SimplePageIndicator.NaviPointLayoutChange)mContext).layoutNavigationPoint(w, h, oldw, oldh);
		
		super.onSizeChanged(w, h, oldw, oldh);
	}
	
	protected void onFinishInflate()
	{
		super.onFinishInflate();
		
		boolean isSimpleLargeScreen = LauncherApplication.isSimpleScreenLarge();
		if (isSimpleLargeScreen){
			int childCount = getChildCount();
			//Log.e(TAG, "onFinishInflate##1, childCount=" + childCount);
			if (childCount >= 3){
				removeViewAt(2);
			}
			//Log.e(TAG, "onFinishInflate##2, childCount=" + childCount);
		}
		
		for (int i = 0; i < getChildCount(); i++)
			((ViewGroup) getChildAt(i)).setLayerType(LAYER_TYPE_HARDWARE, mPaint);
	}
	
	// 从workspace中删除应用项
	public boolean removeItemFromWorkspace(SimpleApplicationInfo app)
	{
		int childCount = getChildCount();
		
		for (int i = 0; i < childCount; i++)
		{
			SimpleCellLayout cellLayout = (SimpleCellLayout)getChildAt(i);
			
			// 找到app位于哪个CellLayout, 遍历横竖
			int countX = cellLayout.getCountX();
		    int countY = cellLayout.getCountY();
		    for (int x = 0; x < countX; x ++){
		    	for(int y = 0; y < countY; y++){
			    	View view = cellLayout.getChildAt(x, y);
			    	if (view != null)
			    	{
			    		ComponentName componentName;
			    		SimpleItemInfo itemInfo;
			    		
			    		Object object = view.getTag();
			    		if (object instanceof SimpleApplicationInfo)
			    		{
			    			itemInfo = (SimpleItemInfo)object;
			    			
			    			if (itemInfo.itemType != SimpleLauncherSettings.SimpleFavorites.ITEM_TYPE_NEED_ADDED)
			    			{
				    			componentName = itemInfo.intent.getComponent();
				    			if (componentName != null && componentName.equals(app.intent.getComponent()))
				    			{
				    				// 找到该APP视图位置并删除之，并把该位置标记为未占用
					    			cellLayout.removeView(view);
					    			cellLayout.setOccupied(x, y, false);
					    		    return true;
					    		}
				    		}
			    		}
			    	}
		    	}
		    }
		    
		}
		
		return true;
	}
	
	@Override
	public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate)
	{
		int index = indexOfChild(child);
		if (index == mCurrentPage && mScroller.isFinished()){
			return false;
		}
		
		snapToPage(index);
		return true;
	}
	
	@Override
	public void scrollTo(int x, int y){
		super.scrollTo(x, y);
	}
	
	protected void setCurrentPage(int currentPage){
		super.setCurrentPage(currentPage);
	}

	void setCurrentScreen(int currentScreen){
		mCurrentPage = currentScreen;
	}

	public void setLauncher(SimpleUILauncher simpleUILauncher){
		mSimpleUILauncher = simpleUILauncher;
	}
	
	public void snapToDefaultScreen()
	{
		if (mContext instanceof SimpleUILauncher){
			((SimpleUILauncher)mContext).getSimplePageIndicatior().setCurrentScreen(mDefaultScreen);
			((SimpleUILauncher)mContext).getSimplePageIndicatior().invalidate();
		}else{
			if (mContext instanceof SimpleFolder){
				((SimpleFolder)mContext).getSimplePageIndicatior().setCurrentScreen(mDefaultScreen);
				((SimpleFolder)mContext).getSimplePageIndicatior().invalidate();
			}
		}
		
		snapToPage(mDefaultScreen);
	}
	
	@Override
	protected void snapToPage(int whichPage, int delta, int duration)
	{
		setCurrentScreen(whichPage);
	    if ((this.mContext instanceof SimpleUILauncher))
	    {
	      ((SimpleUILauncher)mContext).getSimplePageIndicatior().setCurrentScreen(whichPage);
	      ((SimpleUILauncher)mContext).getSimplePageIndicatior().invalidate();
	    }
	    else{
	    	if (mContext instanceof SimpleFolder){
	    		((SimpleFolder)mContext).getSimplePageIndicatior().setCurrentScreen(whichPage);
	  	      	((SimpleFolder)mContext).getSimplePageIndicatior().invalidate();
	    	}
	    }
	    
	    super.snapToPage(whichPage, delta, duration);
	}

	protected void onAttachedToWindow(){
		super.onAttachedToWindow();
	}

	@Override
	public void syncPages(){
		// TODO: 暂无需实现
	}

	@Override
	public void syncPageItems(int page, boolean immediate){
		// TODO: 暂无需实现
	}
	
	void updateApplications(ArrayList<SimpleApplicationInfo> apps)
	{
		int size = apps.size();
		for (int i = 0; i < size; i++)
		{
			if (!updateSimpleApplicationInfo((SimpleApplicationInfo)apps.get(i)))
				mSimpleUILauncher.getSimpleModel().refreshApp();
		}
	}
	
	// 更新应用信息
	public boolean updateSimpleApplicationInfo(SimpleApplicationInfo newApp)
	{
		int count = getChildCount();
		for (int i = 0; i < count; i ++){
			SimpleCellLayout cellLayout = (SimpleCellLayout)getChildAt(i);
			
			int countX = SimpleCellLayout.SIMPLEUI_COUNTX;
		    int countY = SimpleCellLayout.SIMPLEUI_COUNTY;
		    for (int x = 0; x < countX; x ++){
		    	for(int y = 0; y < countY; y++){
		    		View view = cellLayout.getChildAt(x, y);
			    	if (view != null)
			    	{
			    		ComponentName componentName;
			    		SimpleApplicationInfo curApp;
			    		
			    		Object object = view.getTag();
			    		if (object instanceof SimpleApplicationInfo)
			    		{
			    			curApp = (SimpleApplicationInfo)object;
			    			
			    			if (curApp.intent != null)
			    			{
				    			componentName = curApp.intent.getComponent();
				    			if (componentName != null && newApp.componentName.equals(componentName)
				    					&& Intent.ACTION_MAIN.equals(curApp.intent.getAction()) && curApp.itemType == 0)
				    			{
				    				// 找到该APP视图位置更新之
				    				curApp.setIcon(mSimpleIconCache.getIcon(curApp.intent)); // 更新图标缓存
				    				curApp.setTitle(mSimpleIconCache.getTitle(curApp.intent));
				    				// 不是固定APP可以改图标
				    				if (!newApp.isPresetApp)
				    					((SimpleBubbleView)view).setAppIcon(curApp.getIcon(mSimpleIconCache));
				    				((SimpleBubbleView)view).setAppTitle(curApp.title.toString());
					    		    return true;
					    		}else{
					    			Log.w(TAG, "updateSimpleApplicationInfo: The view returned from simpleCellLayout.getChildAt is null.");
					    		}
				    		}
			    		}
			    	}
		    	}
		    }
		}
		
		return false;
	}
	
	
	public static class SavedState extends View.BaseSavedState
	{
		int currentScreen = -1;
		
		private SavedState(Parcel in){
			super(in);
			this.currentScreen = in.readInt();
		}

		SavedState(Parcelable superState){
			super(superState);
		}

		public void writeToParcel(Parcel out, int flags)
		{
			super.writeToParcel(out, flags);
			out.writeInt(currentScreen);
		}
		
		public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator(){
			public SimpleWorkspace.SavedState[] newArray(int size){
				return new SavedState[size];
			}
			
			@Override
			public Object createFromParcel(Parcel in){
				return new SavedState(in);
			}
		};
	}
}
